#!/usr/bin/env python

import argparse
import os
import subprocess
import sys
import platform

from lib.config import MIPS64EL_GCC, set_mips64el_env, get_output_dir, \
                       SOURCE_ROOT, VENDOR_DIR, DEPOT_TOOLS_DIR, \
                       COMPONENTS

from lib.ninja import run as run_ninja


def main():
  args = parse_args()
  target_arch = args.target_arch

  env = os.environ.copy()
  env['PATH'] = os.pathsep.join([DEPOT_TOOLS_DIR, env['PATH']])
  if sys.platform in ['win32', 'cygwin']:
    env['DEPOT_TOOLS_WIN_TOOLCHAIN'] = '0'
  elif target_arch == 'arm64':
    binutils_dir = os.path.join(VENDOR_DIR, 'binutils-aarch64')
    env['LD_LIBRARY_PATH'] = binutils_dir + '/usr/x86_64-linux-gnu/aarch64-linux-gnu/lib'
    env['PATH'] = os.pathsep.join([binutils_dir + '/usr/bin', env['PATH']])
  elif target_arch == 'mips64el':
    set_mips64el_env(env)

  os.chdir(SOURCE_ROOT)

  # Build everything by default.
  components_to_build = list(COMPONENTS)

  if args.debug:
    components_to_build = ['shared_library', 'ffmpeg']
  elif args.release:
    components_to_build = ['static_library', 'ffmpeg']
  elif args.component is not None:
    components_to_build = args.component
  elif "arm" not in target_arch:
    components_to_build.remove('native_mksnapshot')

  for component in components_to_build:
    out_dir = get_output_dir(SOURCE_ROOT, target_arch, component)
    target = 'libchromiumcontent/chromiumcontent:chromiumcontent'
    if component == 'tests':
      target = 'libchromiumcontent/chromiumcontent:chromiumcontent_tests'
    if component == 'native_mksnapshot':
      target = 'v8:mksnapshot'
    run_ninja(os.path.relpath(out_dir), target=target, env=env)

    if component == 'static_library':
      subenv = env.copy()
      subenv['CHROMIUMCONTENT_2ND_PASS'] = '1'
      target = 'libchromiumcontent/chromiumcontent:libs'
      run_ninja(os.path.relpath(out_dir), target=target, env=subenv)


def parse_args():
  parser = argparse.ArgumentParser(description='Build libchromiumcontent')

  parser.add_argument('-t', '--target_arch', default='x64',
                      choices=['arm', 'arm64', 'ia32', 'mips64el', 'x64'])

  what_to_build_group = parser.add_mutually_exclusive_group()
  what_to_build_group.add_argument('-c', '--component', nargs='+', default=None,
                                   choices=COMPONENTS)
  what_to_build_group.add_argument('-D', '--debug', action='store_true',
                                   help='Build debug configuration')
  what_to_build_group.add_argument('-R', '--release', action='store_true',
                                   help='Build release configuration')

  return parser.parse_args()


if __name__ == '__main__':
    sys.exit(main())
